/* eslint-disable no-dupe-class-members */
import React, { PureComponent, Fragment } from 'react';
import { Card, Button, Tabs, DatePicker, Row, Checkbox, Col, Select } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import moment from 'moment';
import PageEmpty from '@/components/PageEmpty';
import qs from 'qs';
import AuthorizedButton from '@/components/AuthorizedButton';
import styles from './index.less';
import { BaseTable, utils } from '@/components/BaseTable';
import { getTitleTree, getFixedColumns } from './utils/treeUtils';

const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  all: state.SupplyAndMarketingMonthly.all,
  items: state.SupplyAndMarketingMonthly.items,
  expandedRowKeys: state.SupplyAndMarketingMonthly.expandedRowKeys,
  level: state.SupplyAndMarketingMonthly.level,
}))
export default class SupplyAndMarketingMonthly extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyTitle: '数据加载中...',
      endTime: moment().format('YYYY-MM'),
      attributesCheckeds: ['套数', '面积', '均价', '金额'],
    };
  }

  // 初始化
  componentDidMount() {
    this.getItems(this.state.endTime);
  }

  // 请求供货计划报表对比
  getItems = deadline => {
    this.setState({ emptyTitle: '数据加载中...' });
    const { dispatch } = this.props;
    const self = this;
    const params = {
      deadline,
    };
    dispatch({
      type: 'SupplyAndMarketingMonthly/init',
      payload: { params },
      callback: () => self.setState({ emptyTitle: '暂无月度供货明细数据' }),
    });
  };

  // 多选
  onChangeAttributesCheckeds = checkedValues => {
    this.setState({
      attributesCheckeds: checkedValues,
    });
  };

  // 层级
  onChangeLevel = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'SupplyAndMarketingMonthly/level',
      payload: { level: value },
    });
  };

  // 截至日期
  handleDeadline = (field, value) => {
    this.setState({
      endTime: value,
    });
    this.getItems(value);
  };

  render() {
    const { emptyTitle, attributesCheckeds, endTime } = this.state;
    const { expandedRowKeys, items, level } = this.props;
    let titleTree = [];
    let fixedColumns = [];
    titleTree = getTitleTree(attributesCheckeds, endTime);
    fixedColumns = getFixedColumns(titleTree, attributesCheckeds);
    const headerRenderer = utils.getHeaderRenderer(titleTree, 2);
    const params = {
      deadline: endTime,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    return (
      <PageHeaderWrapper
        className={styles.SignPlanProgress}
        breadcrumb={null}
        title={<></>}
        extra={
          <>
            截止年月：
            <DatePicker.MonthPicker
              allowClear={false}
              onChange={this.handleDeadline}
              value={moment(endTime)}
              format="YYYY-MM"
              disabledDate={current => current && current > moment().endOf('day')}
            />
            &nbsp;&nbsp;
            <AuthorizedButton authority="SupplyAndMarketingMonthly_Export">
              <Button
                disabled={items.length <= 0}
                className="yellow-button"
                target="_blank"
                href={`${process.env.apiUrl}/api/v1/report/supplyMonthlyDetailReportExport?${exportQueryString}`}
              >
                导出报表
              </Button>
            </AuthorizedButton>
          </>
        }
      >
        <Card>
          {items.length > 0 && expandedRowKeys.length > 0 ? (
            <Fragment>
              <Row align="middle" type="flex" justify="space-between">
                <Col>
                  显示：
                  <Select defaultValue="最新全盘动态" style={{ width: 120 }} size="small">
                    <Option value="region">最新全盘动态</Option>
                  </Select>
                  &nbsp;&nbsp;
                  <Checkbox.Group
                    options={['套数', '面积', '均价', '金额']}
                    value={attributesCheckeds}
                    onChange={this.onChangeAttributesCheckeds}
                  />
                </Col>
                <Col>
                  层级：
                  <Select
                    value={level}
                    style={{ width: 120 }}
                    onChange={this.onChangeLevel}
                    size="small"
                  >
                    <Option value="region">区域</Option>
                    <Option value="cityCompany">城市公司</Option>
                    <Option value="project">项目</Option>
                    <Option value="stage">分期</Option>
                  </Select>
                </Col>
              </Row>
              <BaseTable
                subtractHeight="185px"
                defaultExpandedRowKeys={expandedRowKeys}
                expandColumnKey="name"
                fixedColumns={fixedColumns}
                headerHeight={[30, 30, 60]}
                headerRenderer={headerRenderer}
                treeData={items}
              />
            </Fragment>
          ) : (
            <PageEmpty emptyTitle={emptyTitle} />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}
